package com.dpiinc.TechPage.adapter

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.TransformationUtils
import java.security.MessageDigest

/**
 *
 * 无论图片长宽比如何，横向撑满屏幕，纵向按比例缩放，上对齐显示，超出部分裁剪
 *
 * Created by X on 2018/8/2.
 */
class TopCrop : BitmapTransformation() {

    companion object {
        private const val ID = "com.aiwrite.bitmap.TopCrop"
        private const val PAINT_FLAGS = Paint.DITHER_FLAG or Paint.FILTER_BITMAP_FLAG
        private val DEFAULT_PAINT = Paint(PAINT_FLAGS)
        private val ID_BYTES = ID.toByteArray(Key.CHARSET)
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(ID_BYTES)
    }


    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
        return topCrop(pool, toTransform, outWidth, outHeight)
    }

    /**
     * A potentially expensive operation to crop the given Bitmap so that it fills the given
     * dimensions. This operation is significantly less expensive in terms of memory if a mutable
     * Bitmap with the given dimensions is passed in as well.
     *
     * @param pool     The BitmapPool to obtain a bitmap from.
     * @param inBitmap   The Bitmap to resize.
     * @param width    The width in pixels of the final Bitmap.
     * @param height   The height in pixels of the final Bitmap.
     * @return The resized Bitmap (will be recycled if recycled is not null).
     */
    private fun topCrop(pool: BitmapPool, inBitmap: Bitmap, width: Int,
                        height: Int): Bitmap {
        if (inBitmap.width == width && inBitmap.height == height) {
            return inBitmap
        }
        // From ImageView/Bitmap.createScaledBitmap.
        val scale: Float
        val dx: Float
        val dy: Float
        val m = Matrix()
        //无论图片长宽比如何，横向撑满屏幕，纵向按比例缩放，上对齐显示
//        if (inBitmap.width * height > width * inBitmap.height) {
//            scale = height.toFloat() / inBitmap.height.toFloat()
//            dx = (width - inBitmap.width * scale) * 0.5f
//            dy = 0f
//        } else {
            scale = width.toFloat() / inBitmap.width.toFloat()
            dx = 0f
//                dy = (height - inBitmap.height * scale) * 0.5f
            dy = 0f
//        }

        m.setScale(scale, scale)
        m.postTranslate((dx + 0.5f).toInt().toFloat(), (dy + 0.5f).toInt().toFloat())

        val result = pool.get(width, height, getNonNullConfig(inBitmap))
        // We don't add or remove alpha, so keep the alpha setting of the Bitmap we were given.
        TransformationUtils.setAlpha(inBitmap, result)

        applyMatrix(inBitmap, result, m)
        return result
    }

    private fun getNonNullConfig(bitmap: Bitmap): Bitmap.Config {
        return if (bitmap.config != null) bitmap.config else Bitmap.Config.ARGB_8888
    }

    private fun applyMatrix(inBitmap: Bitmap, targetBitmap: Bitmap,
                            matrix: Matrix) {
//            BITMAP_DRAWABLE_LOCK.lock()
//            try {
        val canvas = Canvas(targetBitmap)
        canvas.drawBitmap(inBitmap, matrix, DEFAULT_PAINT)
//                clear(canvas)
//            } finally {
//                BITMAP_DRAWABLE_LOCK.unlock()
//            }
    }

    override fun hashCode(): Int {
        return ID.hashCode()
    }

    override fun equals(other: Any?): Boolean {
        return other is TopCrop
    }
}